package org.springframework.android.showcase.location;

import org.iside.android.showcase.AbstractAsyncActivity;
import org.iside.android.showcase.R;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import android.content.Context;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.LocationListener;

public class CustomerLocation extends AbstractAsyncActivity {
    
    LocationListener mLocationListener = null;//create时注册此listener，Destroy时需要Remove
    
    protected void onCreate(Bundle savedInstanceState) {
        
        super.onCreate(savedInstanceState);
        setContentView(R.layout.customer_location);
        
        BMapApiDemoApp app = (BMapApiDemoApp)this.getApplication();
        if (app.mBMapMan == null) {
            app.mBMapMan = new BMapManager(getApplication());
            app.mBMapMan.init(app.mStrKey, new BMapApiDemoApp.MyGeneralListener());
        }
        app.mBMapMan.start();
        

        // 注册定位事件
        mLocationListener = new LocationListener(){

            @Override
            public void onLocationChanged(Location location) {
                if(location != null){
//                    String strLog = String.format("您当前的位置:\r\n" +
//                            "纬度:%f\r\n" +
//                            "经度:%f",
//                            location.getLongitude(), location.getLatitude());

//                    TextView mainText = (TextView)findViewById(R.id.textview);
//                    mainText.setText(strLog);
                    
                    TextView textlat = (TextView)findViewById(R.id.textlat);
                    textlat.setText("" + location.getLatitude());
                    
                    TextView textlon = (TextView)findViewById(R.id.textlon);
                    textlon.setText("" + location.getLongitude());
                    
                    // save location to DB
//                    new PostMessageTask(location.getLongitude(), location.getLatitude()).execute();
                }
            }
        };
    }

    @Override
    protected void onPause() {
        BMapApiDemoApp app = (BMapApiDemoApp)this.getApplication();
        // 移除listener
        app.mBMapMan.getLocationManager().removeUpdates(mLocationListener);
        app.mBMapMan.stop();
        super.onPause();
    }
    
    @Override
    protected void onResume() {
        BMapApiDemoApp app = (BMapApiDemoApp)this.getApplication();
        // 注册Listener
        app.mBMapMan.getLocationManager().requestLocationUpdates(mLocationListener);
        app.mBMapMan.start();
        super.onResume();
    }
    
    public void saveLocation(View v) {
        TextView textlat = (TextView)findViewById(R.id.textlat);
        TextView textlon = (TextView)findViewById(R.id.textlon);
        TextView localaddress = (TextView)findViewById(R.id.localaddress);
        TextView phoneNumber = (TextView)findViewById(R.id.phonenumber);
        
        new PostMessageTask(textlon.getText().toString(), textlat.getText().toString(), 
                localaddress.getText().toString(), phoneNumber.getText().toString()).execute();
    }
    
    public void findTaxiNearby(View v) {
        //TODO
        Toast.makeText(this, "功能开发中，敬请期待。。。。", Toast.LENGTH_LONG).show();
    }
    
    private class PostMessageTask extends AsyncTask<Void, Void, String> {

        private MultiValueMap<String, String> message = new LinkedMultiValueMap<String, String>();

        public PostMessageTask(String longitude, String latitude, String address, String phoneNumber) {
            message.add("lon", longitude);
            message.add("lat", latitude);
            message.add("addr", address);
            message.add("pn", phoneNumber);
            TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            Log.e(TAG, "======================" + tm.getDeviceId());
            message.add("customerid", tm.getDeviceId());
        }

        @Override
        protected void onPreExecute() {
            // before the network request begins, show a progress indicator
            showLoadingProgressDialog();
        }

        @Override
        protected String doInBackground(Void... params) {
            try {
                // The URL for making the POST request
                final String url = getString(R.string.base_uri) + "/savecustomerlocation";

                // Create a new RestTemplate instance
                RestTemplate restTemplate = new RestTemplate();

                // Make the network request, posting the message, expecting a
                // String in response from the server
                ResponseEntity<String> response = restTemplate.postForEntity(url, message, String.class);

                // Return the response body to display to the user
                return response.getBody();
            } catch (Exception e) {
                Log.e(TAG, e.getMessage(), e);
            }

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // after the network request completes, hid the progress indicator
            dismissProgressDialog();

            // return the response body to the calling class
            showResult(result);
        }
    }
    
    private void showResult(String result) {
        if (result != null) {
            // display a notification to the user with the response message
            Log.e(TAG, result);
            Toast.makeText(this, "您已成功发出招车请求，请等待；\n或者查看附近的出租车信息，主动联系。", Toast.LENGTH_LONG).show();
            this.onPause();
        } else {
            Toast.makeText(this, "亲，定位过程发生故障,请检查网络!", Toast.LENGTH_LONG).show();
        }
    }
}
